package com.sali.双指针;

/**
 * @author sali
 * @date 2025/5/13 9:20
 */
public class JZ_22 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(0);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode listNode = FindKthToTail(node1, 5);
        System.out.println(listNode);
    }

    public static ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        if ( pHead == null ) {
            return pHead;
        }
        if ( k == 0 ) {
            return null;
        }

        ListNode slowNode = pHead;
        ListNode fastNode = pHead;
        for ( int i = 0; i < k - 1; i++ ) {
            fastNode = fastNode.next;
            if ( fastNode == null ) {
                return null;
            }
        }
        while ( fastNode.next != null ) {
            slowNode = slowNode.next;
            fastNode = fastNode.next;
        }
        return slowNode;
    }

}
class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
  }